package com.zzl.study.auth.security;

import com.zzl.study.auth.domain.SysUserEntity;
import com.zzl.study.auth.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhangzl
 * @date: 2023/12/11 11:03
 * @version: 1.0
 * @description: 用户详情查询接口实现类
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 手机号正则表达式
     */
    private static final String TEL_REGEX = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";

    /**
     * 手机号校验格式
     */
    private static final Pattern TEL_PATTERN = Pattern.compile(TEL_REGEX);

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity sysUserEntity = null;
        if (TEL_PATTERN.matcher(username).matches()) {
            // 手机号登录
            sysUserEntity = this.sysUserService.selectByTel(username);
        } else {
            // 用户名登录
            sysUserEntity = this.sysUserService.selectByUsername(username);
        }
        if (sysUserEntity == null) {
            throw new UsernameNotFoundException("用户名/手机号" + username + "不存在!");
        }
        // TODO: 角色可以再定义一个角色表做关联查询获取
        List<SimpleGrantedAuthority> grantedAuthorityList = Stream.of("USER").map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new User(username, sysUserEntity.getPassword(), grantedAuthorityList);
    }

}
